<?php
class CacheManager{
	static $instance;
	
	var $data = array();
	/**
	 *
	 * @var Controller
	 */
	var $c = null;
	
	/**
	 * @return CacheManager
	 */
	static function getInstance(){
		if(!self::$instance){
			$class = __CLASS__;
			self::$instance = new $class();
		}
		return self::$instance;
	}
	
	public function __construct(){
		$this->c = new Controller('','', false);
	}
	
	public function refresh($app, $controller='', $uid=null){
		$key = $app . '_' .$controller .'_'. ($uid?$uid:$this->c->getUid());
		Cache::getInstance()->save(array(), $key);
		$this->data[$key] = array();
	}
	
	public function get($key, $refresh = false){
		$app = $key['app'] . '_' . $key['controller'] . '_' . (key_exists('uid', $key)?$key['uid']:$this->c->getUid());
		$cache_key = Cache::makeFunctionKey($key['func'][0], $key['func'][1]);
		if(!key_exists($app, $this->data)){
			$this->data[$app] = Cache::getInstance()->load($app);
		}
		if($this->data[$app] && key_exists($cache_key, $this->data[$app])){
			$refresh = false || $refresh;
		}else{
			$refresh = true;
		}
		$ret = Cache::cacheFunction(
			$key['func'][0], 
			$key['func'][1], 
			$refresh, 
			$_SERVER['APPS'][$key['app']]['cache_life']?$_SERVER['APPS'][$key['app']]['cache_life']:1800
		);
		if($refresh){
			$this->set($key, 1);
		}
		return $ret;
	}
	
	public function set($key, $value){
		$app = $key['app'] . '_' . $key['controller'] . "_" . (key_exists('uid', $key)?$key['uid']:$this->c->getUid());
		$cache_key = Cache::makeFunctionKey($key['func'][0], $key['func'][1]);
		$this->data[$app][$cache_key] = $value;
		Cache::getInstance()->save($this->data[$app], $app);
	}
}